using Lzfy_His_Service.Models;
using Lzfy_His_Service.Services;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;

namespace Lzfy_His_Service.Controllers
{
    /// <summary>
    /// 企业微信OAuth2.0控制器
    /// </summary>
    [ApiController]
    [Route("api/[controller]")]
    public class WeChatWorkController : ControllerBase
    {
        private readonly IWeChatWorkService _weChatWorkService;
        private readonly WeChatWorkConfig _config;
        private readonly ILogger<WeChatWorkController> _logger;

        public WeChatWorkController(
            IWeChatWorkService weChatWorkService,
            IOptions<WeChatWorkConfig> config,
            ILogger<WeChatWorkController> logger)
        {
            _weChatWorkService = weChatWorkService;
            _config = config.Value;
            _logger = logger;
        }

        /// <summary>
        /// 获取企业微信授权URL
        /// </summary>
        /// <param name="redirectUri">回调地址（可选）</param>
        /// <param name="state">状态参数（可选）</param>
        /// <returns>授权URL响应</returns>
        [HttpPost("auth-url")]
        public async Task<ActionResult<ApiResponse<WeChatWorkAuthUrlResponse>>> GetAuthUrl([FromQuery] string? redirectUri = null, [FromQuery] string? state = null)
        {
            try
            {
                _logger.LogInformation("获取企业微信授权URL请求: RedirectUri={RedirectUri}, State={State}", redirectUri, state);

                var result = await _weChatWorkService.GetAuthUrlAsync(redirectUri, state);

                return Ok(new ApiResponse<WeChatWorkAuthUrlResponse>
                {
                    Success = true,
                    Data = result,
                    Message = "获取授权URL成功"
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取企业微信授权URL失败");
                return BadRequest(new ApiResponse<WeChatWorkAuthUrlResponse>
                {
                    Success = false,
                    Message = "获取授权URL失败：" + ex.Message
                });
            }
        }

        /// <summary>
        /// 获取企业微信授权URL（GET）
        /// </summary>
        /// <param name="redirectUri">回调地址（可选）</param>
        /// <param name="state">状态参数（可选）</param>
        /// <returns>授权URL响应</returns>
        [HttpGet("auth-url")]
        public async Task<ActionResult<ApiResponse<WeChatWorkAuthUrlResponse>>> GetAuthUrlByGet([FromQuery] string? redirectUri = null, [FromQuery] string? state = null)
        {
            try
            {
                _logger.LogInformation("[GET] 获取企业微信授权URL请求: RedirectUri={RedirectUri}, State={State}", redirectUri, state);

                var result = await _weChatWorkService.GetAuthUrlAsync(redirectUri, state);

                return Ok(new ApiResponse<WeChatWorkAuthUrlResponse>
                {
                    Success = true,
                    Data = result,
                    Message = "获取授权URL成功"
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "[GET] 获取企业微信授权URL失败");
                return BadRequest(new ApiResponse<WeChatWorkAuthUrlResponse>
                {
                    Success = false,
                    Message = "获取授权URL失败：" + ex.Message
                });
            }
        }

        /// <summary>
        /// 企业微信OAuth2.0回调处理
        /// </summary>
        /// <param name="code">授权码</param>
        /// <param name="state">状态参数</param>
        /// <returns>重定向到前端页面</returns>
        [HttpGet("callback")]
        public async Task<IActionResult> Callback([FromQuery] string code, [FromQuery] string? state = null)
        {
            try
            {
                _logger.LogInformation("企业微信OAuth2.0回调: Code={Code}, State={State}", code, state);

                if (string.IsNullOrEmpty(code))
                {
                    _logger.LogWarning("回调参数code为空");
                    return Redirect($"{_config.FrontendErrorUrl}?error=missing_code&message=授权码缺失");
                }

                // 执行登录
                var loginResult = await _weChatWorkService.LoginAsync(code, state);

                if (loginResult.Success && !string.IsNullOrEmpty(loginResult.Token))
                {
                    // 登录成功，重定向到前端成功页面，携带token
                    var successUrl = $"{_config.FrontendSuccessUrl}?token={loginResult.Token}&userId={loginResult.UserInfo?.UserId}&name={Uri.EscapeDataString(loginResult.UserInfo?.Name ?? "")}";
                    _logger.LogInformation("企业微信登录成功，重定向到: {SuccessUrl}", successUrl);
                    return Redirect(successUrl);
                }
                else
                {
                    // 登录失败，重定向到前端错误页面
                    var errorUrl = $"{_config.FrontendErrorUrl}?error=login_failed&message={Uri.EscapeDataString(loginResult.Message)}";
                    _logger.LogWarning("企业微信登录失败: {Message}", loginResult.Message);
                    return Redirect(errorUrl);
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "企业微信OAuth2.0回调处理失败");
                var errorUrl = $"{_config.FrontendErrorUrl}?error=callback_error&message={Uri.EscapeDataString("回调处理失败")}";
                return Redirect(errorUrl);
            }
        }

        /// <summary>
        /// 企业微信登录（API方式）
        /// </summary>
        /// <param name="request">登录请求</param>
        /// <returns>登录响应</returns>
        [HttpPost("login")]
        public async Task<ActionResult<ApiResponse<WeChatWorkLoginResponse>>> Login([FromBody] WeChatWorkAuthRequest request)
        {
            try
            {
                _logger.LogInformation("企业微信API登录请求: Code={Code}", request.Code);

                if (!ModelState.IsValid)
                {
                    return BadRequest(new ApiResponse<WeChatWorkLoginResponse>
                    {
                        Success = false,
                        Message = "请求参数无效"
                    });
                }

                var result = await _weChatWorkService.LoginAsync(request.Code, request.State);

                if (result.Success)
                {
                    return Ok(new ApiResponse<WeChatWorkLoginResponse>
                    {
                        Success = true,
                        Data = result,
                        Message = "登录成功"
                    });
                }
                else
                {
                    return BadRequest(new ApiResponse<WeChatWorkLoginResponse>
                    {
                        Success = false,
                        Data = result,
                        Message = result.Message
                    });
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "企业微信API登录失败");
                return StatusCode(500, new ApiResponse<WeChatWorkLoginResponse>
                {
                    Success = false,
                    Message = "登录失败：" + ex.Message
                });
            }
        }

        /// <summary>
        /// 获取用户信息
        /// </summary>
        /// <param name="code">授权码</param>
        /// <returns>用户信息</returns>
        [HttpGet("user-info")]
        public async Task<ActionResult<ApiResponse<WeChatWorkUserInfo>>> GetUserInfo([FromQuery] string code)
        {
            try
            {
                _logger.LogInformation("获取企业微信用户信息: Code={Code}", code);

                if (string.IsNullOrEmpty(code))
                {
                    return BadRequest(new ApiResponse<WeChatWorkUserInfo>
                    {
                        Success = false,
                        Message = "授权码不能为空"
                    });
                }

                var userInfo = await _weChatWorkService.GetUserInfoByCodeAsync(code);

                if (userInfo != null)
                {
                    return Ok(new ApiResponse<WeChatWorkUserInfo>
                    {
                        Success = true,
                        Data = userInfo,
                        Message = "获取用户信息成功"
                    });
                }
                else
                {
                    return BadRequest(new ApiResponse<WeChatWorkUserInfo>
                    {
                        Success = false,
                        Message = "获取用户信息失败"
                    });
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取企业微信用户信息失败");
                return StatusCode(500, new ApiResponse<WeChatWorkUserInfo>
                {
                    Success = false,
                    Message = "获取用户信息失败：" + ex.Message
                });
            }
        }

        /// <summary>
        /// 通过企业微信用户ID查询用户名
        /// </summary>
        /// <param name="request">查询请求</param>
        /// <returns>用户名查询结果</returns>
        [HttpPost("get-username-by-wxuserid")]
        public async Task<ActionResult<ApiResponse<WeChatWorkUsernameResponse>>> GetUsernameByWxUserId([FromBody] WeChatWorkUsernameRequest request)
        {
            try
            {
                _logger.LogInformation("通过企业微信用户ID查询用户名: WxUserId={WxUserId}", request.WxUserId);

                if (string.IsNullOrWhiteSpace(request.WxUserId))
                {
                    return BadRequest(new ApiResponse<WeChatWorkUsernameResponse>
                    {
                        Success = false,
                        Message = "企业微信用户ID不能为空"
                    });
                }

                var result = await _weChatWorkService.GetUsernameByWxUserIdAsync(request.WxUserId);

                if (result.Success)
                {
                    return Ok(new ApiResponse<WeChatWorkUsernameResponse>
                    {
                        Success = true,
                        Data = result,
                        Message = "查询成功"
                    });
                }
                else
                {
                    return NotFound(new ApiResponse<WeChatWorkUsernameResponse>
                    {
                        Success = false,
                        Message = result.Message
                    });
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "通过企业微信用户ID查询用户名失败: WxUserId={WxUserId}", request.WxUserId);
                return StatusCode(500, new ApiResponse<WeChatWorkUsernameResponse>
                {
                    Success = false,
                    Message = "查询用户名失败：" + ex.Message
                });
            }
        }

        /// <summary>
        /// 通过用户名获取用户详细信息
        /// </summary>
        /// <param name="request">查询请求</param>
        /// <returns>用户详细信息</returns>
        [HttpPost("get-user-detail-by-username")]
        public async Task<ActionResult<ApiResponse<WeChatWorkUserDetailResponse>>> GetUserDetailByUsername([FromBody] WeChatWorkUserDetailRequest request)
        {
            try
            {
                _logger.LogInformation("通过用户名获取用户详细信息: Username={Username}", request.Username);

                if (string.IsNullOrWhiteSpace(request.Username))
                {
                    return BadRequest(new ApiResponse<WeChatWorkUserDetailResponse>
                    {
                        Success = false,
                        Message = "用户名不能为空"
                    });
                }

                var result = await _weChatWorkService.GetUserDetailByUsernameAsync(request.Username);

                if (result.Success)
                {
                    return Ok(new ApiResponse<WeChatWorkUserDetailResponse>
                    {
                        Success = true,
                        Data = result,
                        Message = "查询成功"
                    });
                }
                else
                {
                    return NotFound(new ApiResponse<WeChatWorkUserDetailResponse>
                    {
                        Success = false,
                        Message = result.Message
                    });
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "通过用户名获取用户详细信息失败: Username={Username}", request.Username);
                return StatusCode(500, new ApiResponse<WeChatWorkUserDetailResponse>
                {
                    Success = false,
                    Message = "获取用户详细信息失败：" + ex.Message
                });
            }
        }

        /// <summary>
        /// 健康检查
        /// </summary>
        /// <returns>健康状态</returns>
        [HttpGet("health")]
        public IActionResult Health()
        {
            return Ok(new ApiResponse<object>
            {
                Success = true,
                Data = new { Status = "Healthy", Timestamp = DateTime.UtcNow },
                Message = "企业微信服务运行正常"
            });
        }
    }
}